package kayao.client.network.message;

import kayao.client.data.SharedMemory;
import kayao.client.data.Slave;
import kayao.common.KayaoValues;
import kayao.common.NetworkUtils;

public class SubscriberMessage extends Message {

	protected byte []mData;
	
	protected SubscriberMessage(String targetAddress, int retries, int timeoutLength,	int priority, byte[] data) 
	{
		super(targetAddress, retries, timeoutLength, priority);
		mData=data;
		createPacketData();
		
	}

	@Override
	public String type() {
		// TODO Auto-generated method stub
		return "SubscribersMessage";
	}
	/**
	 * It creates the data to be sent about the subscription.
	 */
	@Override
	public void createPacketData() {
		int counter=NetworkUtils.insertByteArrayToInt(mData, 5);
		int id=NetworkUtils.insertByteArrayToInt(mData, 9);
		byte teamid=mData[13];
		byte kingdom=mData[14];
		byte length=mData[15];
		String name="";
		for(int i=0; i<length;i++)
			name+=(char)mData[16+i];

		System.out.println("[SubscriberMessage] (creating packet) Name: "+name+" Is king: " + Slave.isKing() + " King of kingdom: " + SharedMemory.getInstance().getKing().getKingdom() + " Kingdom requested: " + kingdom);
		if(Slave.isKing() && SharedMemory.getInstance().getKing().getKingdom()==kingdom)
			mSendData= SharedMemory.getInstance().getKing().treatSuscriptersRequest(kingdom,mTargetAddress,
				name,id,teamid,counter);
		else
		{
			//if there's not a king anymore
			mSendData=new byte[9];
			byte []value=NetworkUtils.int32ToByte(KayaoValues.MAGIC_NUMBER);
			System.arraycopy(value, 0, mSendData, 0, 4);
			mSendData[4]=KayaoValues.SUSCRIPTION_REQUEST_NEGATIVE_ANSWER;
			NetworkUtils.insertIntToByteArray(mSendData, 5, counter);
		}
	}

}
